package com.music.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.music.R;
import com.music.adapter.MusicListAdapter;
import com.music.utilbean.MediaUtils;
import com.music.utilbean.Mp3Info;

import java.io.File;
import java.util.ArrayList;

@SuppressLint("NewApi")
public class MyMusicListFragment extends Fragment implements OnItemClickListener, OnClickListener {
	private ListView           listView_mymusic;
	private ArrayList<Mp3Info> mp3Infos;
	private Tab2ActivityMusic  tab2Activity;
	private MusicListAdapter   musicListAdapter;
	private ImageView          image_cd, img_go, img_back, img_begin;
	private TextView textmusic, textsinger;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		tab2Activity = (Tab2ActivityMusic) activity;
	}

	public static MyMusicListFragment newInstance() {
		MyMusicListFragment my = new MyMusicListFragment();
		return my;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.local_listview, container, false);//绑定到xml布局文件即fragment页面片段
		listView_mymusic = (ListView) view.findViewById(R.id.listview_mymusic);
		image_cd = (ImageView) view.findViewById(R.id.image_cd);
		img_back = (ImageView) view.findViewById(R.id.imageButton_back);
		img_begin = (ImageView) view.findViewById(R.id.imageButton_begin);
		img_go = (ImageView) view.findViewById(R.id.imageButton_go);
		textmusic = (TextView) view.findViewById(R.id.textmusic);
		textsinger = (TextView) view.findViewById(R.id.textsinger);
		listView_mymusic.setOnItemClickListener(this);
		img_begin.setOnClickListener(this);
		img_back.setOnClickListener(this);
		img_go.setOnClickListener(this);
		image_cd.setOnClickListener(this);
		loadData();

		listView_mymusic.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
											ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("选择操作");
				menu.add(0, 0, 0, "分享");
				menu.add(0, 1, 0, "删除");
				menu.add(0, 2, 0, "取消");
			}
		});
		return view;
	}

	//给菜单项添加事件
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		//info.id得到listview中选择的条目绑定的id
		String id = String.valueOf(info.id);
		switch (item.getItemId()) {
			case 0:
				Log.i("aa", id);
				//分享事件的方法
				tab2Activity.sharemusic(id);
				return true;

			case 1:
				Log.i("bb", id);

				deletemusic(this.getActivity(), Integer.parseInt(id));  //删除歌曲（1、根据Id删除歌曲文件 2、删除媒体库的记录）
				// showlist();
				return true;
			default:
				return super.onContextItemSelected(item);
		}
	}

	//删除歌曲
	public void deletemusic(Context context, int index) {
		mp3Infos = MediaUtils.getMp3Infos(tab2Activity);

		long id = mp3Infos.get(index).getId();

		Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
				MediaStore.Audio.Media._ID + "=" + id, null,
				MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
		String url = null;
		if (cursor.moveToNext()) {
			//String title=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
			//System.out.println(title);//成功打印出名称了
			url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
		}

		//第一步删文件

		System.out.println(url);
		File musicfile = new File(url);
		if (musicfile.exists()) {
			musicfile.delete();
			Toast.makeText(context, "文件删除成功", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(tab2Activity.getApplicationContext(),
					"文件不存在", Toast.LENGTH_LONG).show();
		}
		//第二步删记录
		ContentResolver resolver = context.getContentResolver();
		resolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media._ID + "=?", new String[]{id + ""});
		Toast.makeText(context, "记录删除成功", Toast.LENGTH_SHORT).show();
		MediaScannerConnection.scanFile(tab2Activity.getApplicationContext(), new String[]{Environment
				.getExternalStorageDirectory().getAbsolutePath()}, null, null);
		loadData();
	}

	@Override
	public void onResume() {
		super.onResume();
		tab2Activity.bindplayService();
	}

	@Override
	public void onPause() {
		super.onPause();
		tab2Activity.unbindplayService();//解除绑定播放服务
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	private void loadData() {//加载本地音乐列表
		mp3Infos = MediaUtils.getMp3Infos(tab2Activity);
		musicListAdapter = new MusicListAdapter(tab2Activity, mp3Infos);
		listView_mymusic.setAdapter(musicListAdapter);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		tab2Activity.playService.play(position);
	}

	//回调播放状态下的UI设置
	public void changeUIstateOnplay(int position) {
		if (position >= 0 && position <= mp3Infos.size()) {
			Mp3Info mp3Info = mp3Infos.get(position);
			textmusic.setText(mp3Info.getTitle());
			textsinger.setText(mp3Info.getArtist());
			Bitmap albumBitmap = MediaUtils.getArtwork(tab2Activity, mp3Info.getId(), mp3Info.getAlbumId(), true, true);
			image_cd.setImageBitmap(albumBitmap);
			if (tab2Activity.playService.isplaying()) {
				img_begin.setImageResource(R.drawable.pause);
			} else {
				img_begin.setImageResource(R.drawable.begin);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.imageButton_begin:
				if (tab2Activity.playService.isplaying()) {
					img_begin.setImageResource(R.drawable.begin);
					tab2Activity.playService.pause();
				} else {
					if (tab2Activity.playService.ispause()) {
						img_begin.setImageResource(R.drawable.pause);
						tab2Activity.playService.start();
					} else {
						tab2Activity.playService.play(tab2Activity.sp.getInt("currentposition", tab2Activity.playService.getCurrentPosition()));
					}
				}
				break;
			case R.id.imageButton_back:
				tab2Activity.playService.prev();
				break;
			case R.id.imageButton_go:
				tab2Activity.playService.next();
				break;
			case R.id.image_cd:
				Intent intent = new Intent(tab2Activity, PlayActivityMusic.class);
				startActivity(intent);
				break;
		}
	}

}
